package com.dk.controller;

import com.dk.pojo.User;
import com.dk.service.LoginService;
import com.dk.service.UserService;
import com.dk.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("loginController")
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;

    @RequestMapping("checkCode")
    public void CheckCodeServlet(String time,HttpServletRequest request, HttpServletResponse response) throws IOException {
        //服务器通知浏览器不要缓存
        //System.out.println(time);
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("check_code", checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", response.getOutputStream());
    }

    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    @RequestMapping("login")
    @ResponseBody
    public Integer login(String username, String password, HttpServletRequest request) throws Exception {
        int status = 0;
        if (username == null || username.equals("")
                || password == null || password.equals("")) {
            // 账号密码不能为空
            status = 1;
            return status;
        }
        User user = loginService.login(username);
        if (user == null) {
            // 账号不存在
            status = 2;
            return status;
        }
        if (user.getFlag() >= 3) {
            // 账号被冻结
            status = 3;
            return status;
        }
        boolean b = MD5Utils.validPassword(password,user.getPassword());
        if (!b) {
            // 账号密码错误
            status = 4;
            user.setFlag(user.getFlag() + 1);
            userService.updateFlag(user);
            return status;
        }
        if (user.getFlag() > 0) {
            user.setFlag(0);
            userService.updateFlag(user);
        }

        HttpSession session = request.getSession();
        session.setAttribute("userLogin", user);
        session.setMaxInactiveInterval(600);
        return status;
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("userLogin");
        return "redirect:/";
    }
}